﻿#include <stdio.h>
#include "stdlib.h"
#include "deal.h"

//根据输入的命令判断git的action模式，返回Git值
Git add_action(char* command)
{
	Git git;
	if(!strcmp(command,"init"))
	{
		//printf("*git init*\n");
		git=init;
	}
	else if(!strcmp(command,"status"))
	{
		//printf("*git status*\n");
		git=status;
	}
	else if(!strcmp(command,"add"))
	{
		//printf("*git add*\n");
		git=add;
	}
	else if(!strcmp(command,"commit"))
	{
		//printf("*git commit*\n");
		git=commit;
	}
	else if(!strcmp(command,"reset"))
	{
		//printf("*git reset*\n");
		git=reset;
	}
	else if(!strcmp(command,"rm"))
	{
	//	printf("*git rm*\n");
		git=rm;
	}
	else if(!strcmp(command,"diff"))
	{
	//	printf("*git diff*\n");
		git=diff;
	}
	else
	{
		printf("unknown action\n");
		git=unknown;
	}
	return git;
}

//根据参数的多少来分别处理命令行，打印当前的action
int add_option(const Git git,char options[5][20],char index[5][40])
{
	//printf("\n");
	if(git==init || git==status)
	{
		printf("git %s\n",Get_git(git));
		if(git==init) git_init();
		if(git==status) git_status(index);
	}
	else if(git==add || git==rm)
	{
		printf("git %s %s\n",Get_git(git),options[2]);
		if(git==add) git_add(options[2],index);
	}
	else if(git==diff || git==commit || git==reset)
	{
		printf("git %s %s %s\n",Get_git(git),options[2],options[3]);
		if(git==diff) git_diff(options[2],options[3]);
		if(git==commit) git_commit(options[2],options[3],index);
	}
	return 0;
}

//将git值换为对应的字符串用于打印出来
char* Get_git(const Git git)
{
	if(git==init) return "init";
	else if(git==status) return "status";
	else if(git==add) return "add";
	else if(git==commit) return "commit";
	else if(git==reset) return "reset";
	else if(git==rm) return "rm";
	else if(git==diff) return "diff";
}

//拆分字符串，command为字符串，options为拆分后放入的字符数组，*spacenum为空格数量
int tick(char* command,char options[5][20],int *spacenum) 
{
	int i,j,a[5];
	a[0]=-1;
	for(i=0,j=1;i<strlen(command);i++)
	{
		if(command[i]==' ') 
		{
			a[j++]=i;
			strcut(a[j-2]+1,a[j-1]-1,command,options[j-2]);
			continue;
		}
	}
	strcut(a[j-1]+1,strlen(command)-1,command,options[j-1]);
	*spacenum=j;
	return 0;
}

//截取a字符串，i为始点，j为终点，放入b中
int strcut(int i,int j,char *a,char *b) 
{
	int k,t;
	strcpy(b,"\0");
	for(k=0,t=i;t<j+1;)
	{
		b[k++]=a[t++];
	}
	b[j-i+1]='\0';
	return 0;
}

int index_writein(char index[5][40])
{
	FILE *fp;
	int i;
	if((fp=fopen("./.git/index.txt","wt+"))==NULL)  //以只读方式打开文件
	{
		printf("cannot open txt1\n");
		exit(1);
	}
	for(i=0;i<5;i++)
	{
		fprintf(fp,index[i]);
		fprintf(fp,"\n");
	}
	fclose(fp);
}

int index_get(char index[5][40])
{
	FILE *fp;
	int i;
	if((fp=fopen("./.git/index.txt","wt+"))==NULL)  //以只读方式打开文件
	{
		printf("cannot open txt1\n");
		exit(1);
	}
	for(i=0;i<5;i++)
	{
		fgets(index[i],MAX,fp);
	}
	fclose(fp);
}